import fs from "node:fs";
import path from "node:path";
import * as readline from "node:readline";

export function rmdir(dirPath: string) {
  if (fs.existsSync(dirPath)) {
    const items = fs.readdirSync(dirPath);
    for (const file of items) {
      const filePath = path.join(dirPath, file);
      const stat = fs.statSync(filePath);
      if (stat.isDirectory()) {
        // 如果是文件夹，则递归调用
        rmdir(filePath);
      } else {
        // 如果是文件，则直接删除
        fs.unlinkSync(filePath);
      }
    }
    // 删除空文件夹
    fs.rmSync(dirPath, { force: true, recursive: true });
  }
}

/**
 * 一行一行的读取文件
 * @param file 文件路径
 * @param onLine 行内容处理函数
 */
export async function readFileAllLines(file: string, onLine: (line: string) => void) {
  return new Promise<void>((resolve, reject) => {
    const stream = fs.createReadStream(file, { encoding: "utf-8" });
    const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
    rl.on("line", line => {
      onLine(line);
    });

    rl.on("error", reject);
    rl.on("close", () => resolve());
  });
}

/**
 * 读取简单的配置文件,返回所有有效行
 * @param file 配置文件路径
 */
export async function readSimpleConfigFileAllLines(file: string): Promise<string[]> {
  const lines: string[] = [];
  await readFileAllLines(file, line => {
    line = line.trim();
    if (!line || line.startsWith("#")) return; // 空白行或注释行
    lines.push(line);
  });
  return lines;
}
